package halberd.utils;

import halberd.data.Hsv;
import halberd.data.Rgb;

public class HsvUtils {
	public static void rgb2hsv(int r, int g, int b, Hsv hsv) {
		double min, max, delta, rc, gc, bc;
		rc = (double) r / 255.0;
		gc = (double) g / 255.0;
		bc = (double) b / 255.0;
		max = Math.max(rc, Math.max(gc, bc));
		min = Math.min(rc, Math.min(gc, bc));
		delta = max - min;
		hsv.v = max;
		if (max != 0.0)
			hsv.s = delta / max;
		else
			hsv.s = 0.0;
		if (hsv.s == 0.0) {
			hsv.h = 0.0;
		} else {
			if (rc == max)
				hsv.h = (gc - bc) / delta;
			else if (gc == max)
				hsv.h = 2 + (bc - rc) / delta;
			else if (bc == max)
				hsv.h = 4 + (rc - gc) / delta;
			hsv.h *= 60.0;
			if (hsv.h < 0)
				hsv.h += 360.0;
		}
	}

	public static void hsv2rgb( double h,double s,double v, Rgb rgb) {
		double f, x, y, z;
		int i;
		v *= 255.0;
		if (s == 0.0) {
			rgb.r = rgb.g = rgb.b = (int) v;
		} else {
			while (h < 0)
				h += 360;
			h = (h % 360) / 60.0;
			i = (int) h;
			f = h - i;
			x = v * (1.0 - s);
			y = v * (1.0 - (s * f));
			z = v * (1.0 - (s * (1.0 - f)));
			switch (i) {
			case 0:
				rgb.r = (int) v;
				rgb.g = (int) z;
				rgb.b = (int) x;
				break;
			case 1:
				rgb.r = (int) y;
				rgb.g = (int) v;
				rgb.b = (int) x;
				break;
			case 2:
				rgb.r = (int) x;
				rgb.g = (int) v;
				rgb.b = (int) z;
				break;
			case 3:
				rgb.r = (int) x;
				rgb.g = (int) y;
				rgb.b = (int) v;
				break;
			case 4:
				rgb.r = (int) z;
				rgb.g = (int) x;
				rgb.b = (int) v;
				break;
			case 5:
				rgb.r = (int) v;
				rgb.g = (int) x;
				rgb.b = (int) y;
				break;
			}
		}
	}
	public static void main(String[] args) {
		Rgb rgb=new Rgb();
		hsv2rgb(23,0.9,0.9,rgb);
		System.out.println(rgb.r);
		System.out.println(rgb.g);
		System.out.println(rgb.b);
	}
}
